package com.devin.config;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;

@Component("myAccessDeniedManager")
public class MyAccessDeniedManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        if(authentication==null){
            throw new AccessDeniedException("没有权限");
        }
        Iterator<ConfigAttribute> iterator = collection.iterator();
        if(iterator.hasNext()){
            ConfigAttribute next = iterator.next();
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            String urlNeededRole = next.getAttribute();
            for(GrantedAuthority authority:authorities){
                if(urlNeededRole.equals(authority.getAuthority())){
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足");//认证成功了，但是没有对应的角色权限
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
